import {commonApi} from "../api/api"

async function username(rule, value, callback) {
    let reg = /(^[a-zA-Z0-9]{2,8}$)/
    let result = await commonApi.count("user", {"name": value});
    if (value === '') {
        callback(new Error('请输入用户名'))
    } else if (!reg.test(value)) {
        callback(new Error("请输入2～8位用户名"))
    } else if (result.data.data.count > 0 && value != sessionStorage.getItem("validator.username")) {
        callback(new Error("用户名重复"));
    } else {
        callback();
    }

}


async function roleName(rule, value, callback) {
    let result = await commonApi.count("role", {"name": value});
    if (value === '') {
        callback(new Error('请输入角色名称'))
    } else if (result.data.data.count > 0 && value != sessionStorage.getItem("validator.rolename")) {
        callback(new Error("角色名重复"))
    } else {
        callback()
    }
}


async function organizationName(rule, value, callback) {
    let result = await commonApi.count("organization", {"name": value});
    if (value === '') {
        callback(new Error('请输入部门名称'))
    } else if (result.data.data.count > 0 && value != sessionStorage.getItem("validator.organizationname")) {
        callback(new Error("部门名称重复"))
    } else {
        callback()
    }
}

async function principleName(rule, value, callback) {
    if (value != undefined && value != null) {
        let result = await commonApi.count("user", {"name": value});
        if (result.data.data.count != 1) {
            callback(new Error("用户不存在"));
        } else {
            callback()
        }
    }

}


function phone(rule, value, callback) {
    let reg = /(^[0-9]{6,12}$)/
    if (value === '') {
        callback(new Error('请输入手机号'))
    } else if (!reg.test(value)) {
        callback(new Error("请输入6～12位数字手机号"))
    } else {
        callback()
    }
}

export const validator = {
    username,
    phone,
    roleName,
    organizationName,
    principleName
}